package com.filmatchs.filmatchs;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

import com.filmatchs.R;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MovieAdapter extends ArrayAdapter<Movie> {
	LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
			Context.LAYOUT_INFLATER_SERVICE);
	int resource;
	String response;
	Context context;
	static Movie c;

	static class ViewHolder {
		ImageView image;
		TextView text;
	}

	public MovieAdapter(Context context, int textViewResourceId,
			List<Movie> items) {
		super(context, textViewResourceId, items);
		this.resource = textViewResourceId;
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder;

		c = getItem(position);

		if (convertView == null) {
			convertView = vi.inflate(resource, parent, false);
			holder = new ViewHolder();

			if (c != null) {

				holder.text = (TextView) convertView.findViewById(R.id.text1);
				holder.image = (ImageView) convertView.findViewById(R.id.image);
				convertView.setTag(holder);
			}
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		Drawable drawable = null;
		drawable = LoadImageFromWebOperation(c.getThumb());

		if (drawable == null) {
			drawable = getContext().getResources().getDrawable(R.drawable.icon);
		}

		holder.image.setImageDrawable(drawable);
		holder.text.setText(c.getTitle());

		return convertView;
	}

	private Drawable LoadImageFromWebOperation(String url) {
		try {
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, url);
			return d;
		} catch (Exception e) {
			System.out.println("Exc=" + e);
			return null;
		}
	}

}
